import "./index.less";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import Toolbar from "@/components/ViewComponents/Toolbar";
import { useTranslation } from "react-i18next";
import { Empty, message, Spin } from "antd";
import { patientSynthesisList } from "@/api/SecondmentDictionary";
import { create_emergencies, create_patients, get_emergencies_page } from "@/api/EmergencyDictionary";
import { patientsGet } from "@/api/MedicalExamination";
import { useFetchHistoryData, History } from "@/components/ViewComponents/History/index";
import { useNavigate } from "react-router-dom";
import LogoImg from "@/assets/images/logo.png";
import moment from "moment";
import { useEffect, useState } from "react";
import { listSimpleDept } from "@/api/system/dept";
import { handleTree } from "@/utils/tree";
export default function emergency_reception() {
	const navigate = useNavigate();
	const { t } = useTranslation();
	let [isPatientId, setIspatientId] = useState("");
	const [treeData, setTreeData] = useState([]);
	const [isLoading, setIsLoading] = useState(true);

	let btnList = [
		"save"
		// "edit", "skip", "print", "end"
	];
	const formSchemaBottom: FormSchema[] = [
		// {
		// 	label: "编号",
		// 	field: "id",
		// 	show: false,
		// 	component: "Input"
		// },
		// {
		// 	label: "紧急Id",
		// 	field: "emgId",
		// 	component: "Input",
		// 	// show: false,
		// 	componentProps: {
		// 		disabled: true
		// 	}
		// },
		// {
		// 	label: "转诊ID",
		// 	field: "transId",
		// 	component: "Input",
		// },
		// {
		// 	label: "保险ID",
		// 	field: "insId",
		// 	component: "Input",
		// },
		// {
		// 	label: "检查ID",
		// 	field: "examId",
		// 	component: "Input",
		// },
		// {
		// 	label: "亲属ID",
		// 	field: "famId",
		// 	component: "Input",
		// },
		{
			label: t("felix_ui.time_of_arrival"),
			field: "emgDtime",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.staffId"),
			field: "staffId",
			component: "Input"
		},
		{
			label: t("system.user.deptName"),
			field: "deptId",
			component: "TreeSelect",
			componentProps: {
				treeData,
				fieldNames: {
					value: "id",
					label: "name"
				}
			}
		},
		{
			label: t("felix_ui.evaluation"),
			field: "evaluation",
			component: "Select",
			componentProps: {
				options: [
					{
						label: t("felix_ui.endangered"),
						value: "1"
					},
					{
						label: t("felix_ui.critical"),
						value: "2"
					},
					{
						label: t("felix_ui.emergencyCase"),
						value: "3"
					},
					{
						label: t("felix_ui.subAcute"),
						value: "4"
					},
					{
						label: t("felix_ui.nonEmergency"),
						value: "5"
					}
				]
			}
		},
		{
			label: t("felix_ui.referralType"),
			field: "referralType",
			component: "Select",
			componentProps: {
				options: [
					{ label: t("felix_ui.health_institutions"), value: "1" },
					{ label: t("felix_ui.not_mentioned"), value: "2" },
					{ label: t("felix_ui.orser"), value: "3" }
				],
				onChange: (value: String) => {
					console.log(value);
					if (value == "1") {
						updateSchemaBottom([
							{
								field: "facId",
								componentProps: {
									disabled: false
								}
							}
						]);
					} else {
						updateSchemaBottom([
							{
								field: "facId",
								componentProps: {
									disabled: true
								}
							}
						]);
					}
				}
			}
		},
		{
			label: t("felix_ui.facId"),
			field: "facId",
			component: "Input",
			componentProps: {
				disabled: true
			}
		},
		{
			label: t("felix_ui.emgReason"),
			field: "emgReason",
			component: "Input"
		},
		{
			label: t("felix_ui.status"),
			field: "status",
			component: "Select",
			componentProps: {
				options: [
					{ label: t("felix_ui.open"), value: "0" },
					{ label: t("felix_ui.close"), value: "1" }
				]
			}
		}
	];
	const schemasStart = [
		{
			label: t("felix_ui.admission_time"),
			field: "dateAdmission"
		},
		{
			label: t("felix_ui.adReason"),
			field: "adReason"
		},
		{
			label: t("felix_ui.patient_ID"),
			field: "patId"
		},
		{
			label: t("felix_ui.InsuranceID"),
			field: "insId"
		},
		{
			label: t("felix_ui.adRecievedFrom"),
			field: "adRecievedFrom"
		},
		{
			label: t("felix_ui.doctor"),
			field: "atdDoctor"
		},
		{
			label: t("felix_ui.atdNurse"),
			field: "atdNurse"
		},
		{
			label: t("felix_ui.adStaffId"),
			field: "adStaffId"
		},
		{
			label: t("felix_ui.emgContactName"),
			field: "emgContactName"
		},
		{
			label: t("felix_ui.emgContactPhone"),
			field: "emgContactPhone"
		}
	];
	const schemasEnd = [
		{
			label: t("felix_ui.dcDtime"),
			field: "dcDtime"
		},
		{
			label: t("felix_ui.dcNo"),
			field: "dcNo"
		},
		{
			label: t("felix_ui.trtmtDays"),
			field: "trtmtDays"
		},
		{
			label: t("felix_ui.dcReason"),
			field: "dcReason"
		},
		{
			label: t("felix_ui.isComplication"),
			field: "isComplication"
		},
		{
			label: t("felix_ui.isPathology"),
			field: "isPathology"
		},
		{
			label: t("felix_ui.isDisaster"),
			field: "isDisaster"
		},
		{
			label: t("felix_ui.isRx"),
			field: "isRx"
		}
	];
	const [registerHistory] = useFetchHistoryData({
		api: patientSynthesisList,
		id: isPatientId,
		contents: "createdTime",
		parameter: {
			pageSize: 10,
			pageNo: 1,
			patCardno: isPatientId
		},
		contentList: [
			{
				title: t("felix_ui.ipmAdmission"),
				schemas: schemasStart,
				key: "ipmAdmission"
			},
			{
				title: t("felix_ui.ipmDischarge"),
				schemas: schemasEnd,
				key: "ipmDischarge"
			}
		]
	});
	const [
		formBottom,
		{
			getFieldsValue: getFieldsValueBottom,
			updateSchema: updateSchemaBottom,
			setFieldsValue: setFieldsValueBottom,
			resetFields: resetFieldsBottom
		}
	] = useForm({
		labelWidth: 150,
		schemas: formSchemaBottom,
		autoSubmitOnEnter: false,
		showActionButtonGroup: false,
		baseColProps: { span: 12 }
	});
	const formSchemaTop: FormSchema[] = [
		{
			label: t("felix_ui.pat_cardno"),
			field: "patCardno",
			component: "InputSearch",
			componentProps: {
				onSearch: (val: string) => {
					if (val) getPatientInfo(val);
				}
			},
			rules: [
				{
					required: true,
					message: t("felix_ui.please_enter_cardnum")
				}
			]
		},
		{
			label: t("felix_ui.patient_ID"),
			field: "patientId",
			component: "Input",
			componentProps: {
				disabled: true
			}
		},
		{
			label: t("felix_ui.full_name"),
			field: "fullName",
			component: "Input"
		},
		{
			label: t("felix_ui.age"),
			field: "age",
			component: "Input"
		},
		{
			label: t("felix_ui.citizen_id"),
			field: "citizenId",
			component: "Input",
			rules: [
				{
					required: true,
					message: t("viewComponents.patientInformation.pleaseEnterID")
				}
			]
		},
		{
			label: t("felix_ui.gender"),
			field: "gender",
			component: "Select",
			componentProps: {
				options: [
					{
						label: t("felix_ui.woman"),
						value: 0
					},
					{
						label: t("felix_ui.man"),
						value: 1
					}
				]
			}
		},
		{
			label: t("felix_ui.date_of_birth"),
			field: "birthday",
			component: "DatePicker",
			componentProps: {
				format: "YYYY-MM-DD"
			}
		},
		{
			label: t("felix_ui.ethnicity"),
			field: "ethnicity",
			component: "Input"
		},
		{
			label: t("felix_ui.pat_address"),
			field: "addrCity",
			component: "Input"
		},
		{
			label: t("felix_ui.n_industry"),
			field: "occupation",
			component: "Input"
		},
		{
			label: t("felix_ui.phone_numb"),
			field: "phoneNumb",
			component: "Input"
		},
		{
			label: t("felix_ui.grp_email"),
			field: "emailAddr",
			component: "Input",
			rules: [{ required: true, message: t("felix_ui.please_enter_email"), type: "email" }]
		},
		{
			label: t("felix_ui.house_number"),
			field: "addrHouseno",
			component: "Input"
		},
		{
			label: t("felix_ui.province_city"),
			field: "addrProvince",
			component: "Input"
		}
	];
	const [
		formTop,
		{ getFieldsValue: getFieldsValueTop, setFieldsValue: setFieldsValueTop, resetFields: resetFieldsTop, setFieldValue }
	] = useForm({
		schemas: formSchemaTop,
		showActionButtonGroup: false,
		labelWidth: 150,
		baseColProps: { span: 12 }
	});
	const handleSave = async () => {
		try {
			let valuesTop = await getFieldsValueTop();
			if (valuesTop.birthday) valuesTop.birthday = valuesTop.birthday.split(" ")[0];
			create_patients(valuesTop).then(async res => {
				res && setFieldValue("patientId", res);
				let valuesBottom = await getFieldsValueBottom();
				valuesBottom = {
					...valuesBottom,
					emgDtime: Date.parse(valuesBottom.emgDtime),
					patientId: res,
					patCardno: valuesTop.patCardno
				};
				create_emergencies(valuesBottom).then(async () => {
					message.success(t("felix_ui.successfully"));
					let valuesTop = await getFieldsValueTop();
					navigate("/EmergencyDictionaryR1/4.14", {
						state: {
							patCardno: valuesTop.patCardno
						}
					});
				});
			});
		} catch (err) {
			console.log(err);
		}
	};

	const handlerToolbarAction = async (key: string) => {
		switch (key) {
			case "save":
				handleSave();
				break;
		}
		console.log("key", key);
	};

	const getPatientInfo = async (patCardno: string) => {
		setIspatientId(patCardno);
		const res = await patientsGet({ patCardno });
		if (res) {
			setFieldsValueTop({
				...res,
				birthday: moment(res.birthday)
			});
			const res1 = await get_emergencies_page({ patCardno });
			res1.list[0]
				? setFieldsValueBottom({
						...res1.list[0],
						emgDtime: moment(res1.list[0].emgDtime)
				  })
				: null;
		} else {
			resetFieldsTop(formSchemaTop.slice(1, formSchemaTop.length).map((item: any) => item.field));
			resetFieldsBottom();
		}
	};

	useEffect(() => {
		const getTreeData = async () => {
			try {
				const data = await listSimpleDept();
				let root: any = { id: 0, name: "部门分类", children: [] };
				root.children = handleTree(data, "id", "parentId");
				// 转换数据格式以匹配 TreeSelect 的要求
				const convertToTreeSelectFormat = node => {
					return {
						...node,
						title: node.name,
						value: node.id,
						children: node.children ? node.children.map(convertToTreeSelectFormat) : []
					};
				};
				const newTreeData = [convertToTreeSelectFormat(root)];
				console.log("newTreeData", newTreeData);
				setTreeData(newTreeData);
				setIsLoading(false);
			} catch (error) {
				console.error("Error fetching tree data:", error);
				setIsLoading(false);
			}
		};
		getTreeData();
	}, []);

	return (
		<div className="emergency_reception page flex">
			<div className="content-header block">
				<img className="content-header-logo" src={LogoImg} />
				<div>
					<div className="content-header-title"> {t("felix_ui.home_title_bule")}</div>
					<div className="content-header-subtitle">{t("felix_ui.home_title_black")}</div>
				</div>
			</div>
			<div className="content flex space-between">
				{isLoading ? (
					<div style={{ width: "100%", display: "flex", justifyContent: "center", alignItems: "center" }}>
						<Spin size="large" />
					</div>
				) : (
					<div className="emergency_reception_content">
						<div className="modules_left flex">
							<div className="modules_left_top block overflow-auto">
								<h3>Ⅰ.{t("felix_ui.admin_QR_CODE")}</h3>
								<BasicForm register={formTop}></BasicForm>
							</div>

							<div className="modules_left_bottom block overflow-auto">
								<h3>Ⅱ.{t("felix_ui.info_mation")}</h3>
								<BasicForm register={formBottom} labelWrap={true}></BasicForm>
							</div>
						</div>
						<div className="modules_right block overflow-auto">
							<h3>Ⅲ.{t("felix_ui.patient_Hospital_history")}</h3>
							{isPatientId ? <History register={registerHistory}></History> : <Empty />}
						</div>
					</div>
				)}
				<Toolbar action={handlerToolbarAction} btnList={btnList} />
			</div>
		</div>
	);
}
